import { defineStore } from 'pinia'
import { ref } from 'vue'

export const useThemeStore = defineStore('theme', () => {
  // 主题模式：'light' | 'dark'
  const theme = ref(localStorage.getItem('theme') || 'light')
  
  // 菜单配色：'light' (淡雅) | 'dark' (深色)
  const menuColorScheme = ref(localStorage.getItem('menuColorScheme') || 'light')

  // 应用主题
  const applyTheme = (themeValue) => {
    if (typeof document !== 'undefined') {
      if (themeValue === 'dark') {
        document.documentElement.classList.add('dark')
      } else {
        document.documentElement.classList.remove('dark')
      }
    }
  }

  // 应用菜单配色
  const applyMenuColorScheme = (scheme) => {
    if (typeof document !== 'undefined') {
      if (scheme === 'dark') {
        document.documentElement.classList.add('menu-dark')
        document.documentElement.classList.remove('menu-light')
      } else {
        document.documentElement.classList.add('menu-light')
        document.documentElement.classList.remove('menu-dark')
      }
    }
  }

  // 初始化主题
  const initTheme = () => {
    if (typeof document === 'undefined') return
    
    const savedTheme = localStorage.getItem('theme') || 'light'
    theme.value = savedTheme
    applyTheme(savedTheme)
    
    const savedMenuColorScheme = localStorage.getItem('menuColorScheme') || 'light'
    menuColorScheme.value = savedMenuColorScheme
    applyMenuColorScheme(savedMenuColorScheme)
  }

  // 切换主题
  const toggleTheme = () => {
    theme.value = theme.value === 'light' ? 'dark' : 'light'
    localStorage.setItem('theme', theme.value)
    applyTheme(theme.value)
  }

  // 设置主题
  const setTheme = (themeValue) => {
    theme.value = themeValue
    localStorage.setItem('theme', theme.value)
    applyTheme(theme.value)
  }

  // 切换菜单配色
  const toggleMenuColorScheme = () => {
    menuColorScheme.value = menuColorScheme.value === 'light' ? 'dark' : 'light'
    localStorage.setItem('menuColorScheme', menuColorScheme.value)
    applyMenuColorScheme(menuColorScheme.value)
  }

  // 设置菜单配色
  const setMenuColorScheme = (scheme) => {
    menuColorScheme.value = scheme
    localStorage.setItem('menuColorScheme', menuColorScheme.value)
    applyMenuColorScheme(menuColorScheme.value)
  }

  return {
    theme,
    menuColorScheme,
    toggleTheme,
    setTheme,
    toggleMenuColorScheme,
    setMenuColorScheme,
    initTheme,
  }
})

